<?php 
class Image extends Object
{
	public $Title;
	public $Description;
	public $Filename;
	public $ImageOrder;
	public $Active;
	public $ParentIdField;
	public $ParentId;
	public $FolderPath;
	public $FolderUrl;
	public $ThumbKey;
	public $ProductId;
	public $VariationId;
	public $VariationValueId;
	public $Default;
	
	public function Image($values = '')
	{ 
		if(is_array($values))
		{ self::setValues($values); }
	}
	
	public function getImageOrder() { return intval($this->ImageOrder); }
	public function getParentId() { return intval($this->ParentId); }
	
	public function setImageOrder($val) { $this->ImageOrder=intval($val); }
	public function setParentId($val) { $this->ParentId=intval($val); }
	public function setDefault($val) { $this->Default=intval($val); }
	//$thumb['ADS'][0]['MAXW'] = 960;
	public function render($maxW=0, $maxH=0, $folder='')
	{
		$out = '<img src="';
		if($folder != '')
		{ $out .= $folder; }
		else
		{ $out .= self::getFolderUrl(); }
		$out .= $filename.'"'; 
		if(self::getTitle() != '')
		{ $out .= ' alt="'.self::getTitle().'"'; }
		
		/*
		if(self::getThumbKey() != '')
		{
		}
		*/
		$out .= ' />';
		return $out;
	}
	
	public function getLink($maxW=0, $maxH=0)
	{
		$link = '';
		if(($maxW == 0) && ($maxH == 0))
		{ $link = self::getFolderUrl().self::getFilename(); }
		else
		{
			if($maxH == 0)
			{
				if(is_file(self::getFolderPath().'thumbs/'.$maxW.'_'.self::getFilename())) 
				{ $link = self::getFolderUrl().'thumbs/'.$maxW.'_'.self::getFilename(); } //Check if allready resized
				else 
				{
					//Check the width of original first thumb
					if(is_file(self::getFolderPath().'thumbs/'.self::getFilename()))
					{
						list($width, $height) = getimagesize(self::getFolderPath().'thumbs/'.self::getFilename());
						if($maxW == $width)
						{ $link = self::getFolderUrl().'thumbs/'.self::getFilename(); }
					}
				}
				if($link == '')
				{
					if(is_file(self::getFolderPath().self::getFilename()))
					{
						if(copy(self::getFolderPath().self::getFilename(), self::getFolderPath().'thumbs/'.$maxW.'_'.self::getFilename())) 
						{ 
							self::resizePhoto(self::getFolderPath().'thumbs/'.$maxW.'_'.self::getFilename(), '', $maxW, $maxH);
							$link = self::getFolderUrl().'thumbs/'.$maxW.'_'.self::getFilename();
						}
					}
				}
			}
			else
			{
				if(is_file(self::getFolderPath().'thumbs/'.$maxW.'_'.$maxH.'_'.self::getFilename())) 
				{ $link = self::getFolderUrl().'thumbs/'.$maxW.'_'.$maxH.'_'.self::getFilename(); } //Check if allready resized
				else 
				{
					//Check the width of original first thumb
					if(is_file(self::getFolderPath().'thumbs/'.self::getFilename()))
					{
						list($width, $height) = getimagesize(self::getFolderPath().'thumbs/'.self::getFilename());
						if($maxH == $height)
						{ $link = self::getFolderUrl().'thumbs/'.self::getFilename(); }
					}
				}
				if($link == '')
				{
					if(is_file(self::getFolderPath().self::getFilename()))
					{
						if(copy(self::getFolderPath().self::getFilename(), self::getFolderPath().'thumbs/'.$maxW.'_'.$maxH.'_'.self::getFilename())) 
						{ 
							self::resizePhoto(self::getFolderPath().'thumbs/'.$maxW.'_'.$maxH.'_'.self::getFilename(), '', $maxW, $maxH);
							$link = self::getFolderUrl().'thumbs/'.$maxW.'_'.$maxH.'_'.self::getFilename();
						}
					}
				}
			}
		}
		return $link;
	}
	
	function GetImageFromUrl($link)
	{
	 
	 	return file_get_contents($link);
		//file_put_contents($img, );

	}

	public function update()
	{
		if((self::getId() > 0) && (self::getDataChanged()) && (self::getDataTable() != ''))
		{
			$sql  = 'UPDATE '.DB_PERFIX.self::getDataTable().' SET ';
			if(self::getTitle() != '')
			{ $sql .= '`title`="'.self::formatText(self::getTitle()).'", '; }
			if(self::getDescription() != '')
			{ $sql .= '`description`="'.self::formatText(self::getDescription()).'", '; }
			$sql .= '`filename`="'.self::formatText(self::getFilename()).'", ';
			if((self::getParentIdField() != '') && (self::getParentId() > 0))
			{ $sql .= '`imageOrder`='.self::getImageOrder().', '; }
			$sql .= '`active`='.self::getActive().' ';
			$sql .= ' WHERE id='.self::getId().' ';
			if((self::getParentIdField() != '') && (self::getParentId() > 0))
			{ $sql .= ' AND `'.self::getParentIdField().'`='.self::getParentId().' '; }
			$sql .= ' LIMIT 1;';
			mysql_query($sql);
		}
	}
	
	public function getValidImgExt()
	{
		$extList['gif'] 	= 'image/gif';
		$extList['jpg'] 	= 'image/jpeg';
		$extList['jpeg'] 	= 'image/jpeg';
		$extList['png'] 	= 'image/png';
		return $extList;
	}
	
	public function setValidImgExt($type)
	{
		$file_types  = array(  
		'image/pjpeg'     => 'jpg',
		'image/jpeg'     => 'jpg',
		'image/gif'     => 'gif',
		'image/X-PNG'    => 'png',
		'image/PNG'         => 'png',
		'image/png'     => 'png',
		'image/x-png'     => 'png',
		'image/JPG'     => 'jpg',
		'image/GIF'     => 'gif',
		);
		
		if($file_types[$type] != '')
		{ return $file_types[$type]; }
	}
	
	public function image_valid($type)
	{
		$file_types  = array(  
		'image/pjpeg'     => 'jpg',
		'image/jpeg'     => 'jpg',
		'image/jpeg'     => 'jpeg',
		'image/gif'     => 'gif',
		'image/X-PNG'    => 'png',
		'image/PNG'         => 'png',
		'image/png'     => 'png',
		'image/x-png'     => 'png',
		'image/JPG'     => 'jpg',
		'image/GIF'     => 'gif',
		);
	   
		if(!array_key_exists($type, $file_types))
		{ return false; }
		else
		{ return true; }
	}
	
	public function resizePhoto($file, $type, $width, $height)
	{
		if(is_file($file))
		{
			$fileName = $file;
			if($type != '')
			{ $fileType = $type; }
			else
			{
				$extList = getValidImgExt();
				$info = pathinfo($file);
				if($extList[$info['extension']] != '')
				{ $fileType = $extList[$info['extension']]; }
			}
			
			
			// Check image type
			switch ($fileType) 
			{
				case 'image/pjpeg':
				$fileType = "image/jpeg";
				$ext = ".jpg";
				break;
				case 'image/jpeg':
				$ext = ".jpg";
				break;
				case 'image/x-png':
				$fileType = "image/png";
				$ext = ".png";
				break;
				case 'image/png':
				$ext = ".png";
				break;
				case 'image/gif':
				$ext = ".gif";
				break;
			}
			
			// Get new dimensions
			list($width_orig, $height_orig) = getimagesize($file);
			if((($width_orig > 0) && ($height_orig > 0)) && (($width_orig > $width) || ($height_orig > $height)))
			{
				$ratio_orig = $width_orig/$height_orig;
				
				if ($width/$height > $ratio_orig) 
				{ $width = $height*$ratio_orig; } 
				else 
				{ $height = $width/$ratio_orig; }
				
				// Resample
				$image_p = imagecreatetruecolor($width, $height);
				switch ($fileType) {
					case 'image/pjpeg':
						$newimage = imagecreatefromjpeg($file);
						imagecopyresampled($image_p, $newimage, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
						imagejpeg($image_p, $file, 100);
					break;
					case 'image/jpeg':
						$newimage = imagecreatefromjpeg($file);
						imagecopyresampled($image_p, $newimage, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
						imagejpeg($image_p, $file, 100);
					break;
					case 'image/x-png':
					case 'image/png':
						$newimage = imagecreatefrompng($file);
						
						imagealphablending($image_p, false);
						imagesavealpha($image_p,true);
						$transparent = imagecolorallocatealpha($image_p, 255, 255, 255, 127);
						imagefilledrectangle($image_p, 0, 0, $width, $height, $transparent);
						imagecopyresampled($image_p, $newimage, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
		
						//imagecopyresampled($image_p, $newimage, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
						imagepng($image_p, $file);
					break;
					case 'image/gif':
						$newimage = imagecreatefromgif($file);
						imagecopyresampled($image_p, $newimage, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
						imagegif($image_p, $file);
					break;
				}	
				return true;
			}
			else
			{ return false; }
		}
		else
		{ return false; }
	}
	
	public function smart_resize_image($file, $width, $height, $proportional, $use_linux_command)
	{
		if ( $height <= 0 && $width <= 0 ) 
		{ return false; }
	  
		$info = getimagesize($file);
		$image = '';
	  
		$final_width = 0;
		$final_height = 0;
		list($width_old, $height_old) = $info;
	  
		if ($proportional) 
		{
			$proportion = $width_old / $height_old;
			
			if ( $width > $height && $height != 0) 
			{
				$final_height = $height;
				$final_width = $final_height * $proportion;
			}
			elseif ( $width < $height && $width != 0) 
			{
				$final_width = $width;
				$final_height = $final_width / $proportion;
			}
			elseif ( $width == 0 ) 
			{
				$final_height = $height;
				$final_width = $final_height * $proportion;   
			}
			elseif ( $height == 0) 
			{
				$final_width = $width;
				$final_height = $final_width / $proportion;    
			}
			else 
			{
				$final_width = $width;
				$final_height = $height;
			}
		}
		
		else 
		{
			$final_width = ( $width <= 0 ) ? $width_old : $width;
			$final_height = ( $height <= 0 ) ? $height_old : $height;
		}
	
		switch ( $info[2] ) 
		{
			case IMAGETYPE_GIF:
				$image = imagecreatefromgif($file);
			break;
			case IMAGETYPE_JPEG:
				$image = imagecreatefromjpeg($file);
			break;
			case IMAGETYPE_PNG:
				$image = imagecreatefrompng($file);
			break;
			default:
				return false;
		}
	  
		$image_resized = imagecreatetruecolor( $final_width, $final_height );
		imagecolortransparent($image_resized, imagecolorallocate($image_resized, 0, 0, 0) );
		imagealphablending($image_resized, false);
		imagesavealpha($image_resized, true);
	  
		imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);
	  
		if ( $use_linux_command )
			exec('rm '.$file);
		else
			@unlink($file);
	  
		switch ( $info[2] ) {
			case IMAGETYPE_GIF:
				imagegif($image_resized, $file);
			break;
			case IMAGETYPE_JPEG:
				imagejpeg($image_resized, $file);
			break;
			case IMAGETYPE_PNG:
				imagepng($image_resized, $file);
			break;
			default:
				return false;
		}
		return true;
	}
	
	public function reArrayFiles(&$file_post) 
	{
		$file_ary = array();
		$file_count = count($file_post['name']);
		$file_keys = array_keys($file_post);
		for ($i=0; $i<$file_count; $i++) 
		{
			foreach ($file_keys as $key) 
			{
				$file_ary[$i][$key] = $file_post[$key][$i];
			}
		}
		return $file_ary;
	}
	
	public function makeIcons_MergeCenter($src, $dst, $dstx, $dsty)
	{
		//$src = original image location
		//$dst = destination image location
		//$dstx = user defined width of image
		//$dsty = user defined height of image
		
		$allowedExtensions = 'jpg jpeg gif png';
		
		$name = explode(".", $src);
		$currentExtensions = $name[count($name)-1];
		$extensions = explode(" ", $allowedExtensions);
		
		for($i=0; count($extensions)>$i; $i=$i+1)
		{
			if($extensions[$i]==$currentExtensions)
			{ 
				$extensionOK=1;
				$fileExtension=$extensions[$i];
				break; 
			}
		}
		
		if($extensionOK)
		{
			$size = getImageSize($src);
			$width = $size[0];
			$height = $size[1];
			
			if($width >= $dstx AND $height >= $dsty)
			{
				$proportion_X = $width / $dstx;
				$proportion_Y = $height / $dsty;
				
				if($proportion_X > $proportion_Y )
				{ $proportion = $proportion_Y; }
				else
				{ $proportion = $proportion_X ; }
				$target['width'] = $dstx * $proportion;
				$target['height'] = $dsty * $proportion;
				
				$original['diagonal_center'] = round(sqrt(($width*$width)+($height*$height))/2);
				$target['diagonal_center'] = round(sqrt(($target['width']*$target['width'])+($target['height']*$target['height']))/2);
				
				$crop = round($original['diagonal_center'] - $target['diagonal_center']);
				
				if($proportion_X < $proportion_Y )
				{
					$target['x'] = 0;
					$target['y'] = round((($height/2)*$crop)/$target['diagonal_center']);
				}
				else
				{
					$target['x'] =  round((($width/2)*$crop)/$target['diagonal_center']);
					$target['y'] = 0;
				}
				
				if($fileExtension == "jpg" OR $fileExtension=='jpeg')
				{ $from = ImageCreateFromJpeg($src); }
				elseif ($fileExtension == "gif")
				{ $from = ImageCreateFromGIF($src); }
				elseif ($fileExtension == 'png')
				{ $from = imageCreateFromPNG($src); }
				
				$new = ImageCreateTrueColor ($dstx,$dsty);
				
				imagecopyresampled ($new,  $from,  0, 0, $target['x'],
				$target['y'], $dstx, $dsty, $target['width'], $target['height']);
				
				if($fileExtension == "jpg" OR $fileExtension == 'jpeg')
				{ imagejpeg($new, $dst, 70); }
				elseif ($fileExtension == "gif")
				{ imagegif($new, $dst); }
				elseif ($fileExtension == 'png')
				{ imagepng($new, $dst); }
			}
		}
	}
	
	public function moveRenameImageWithThumbs($oldPath, $newPath, $oldFilename, $newFilename='', $thbIndex='')
	{
		if($newFilename == '')
		{ $newFilename = $oldFilename; }
		
		if(($oldFilename != '') && ($newFilename != '') && ($oldPath != $newPath))
		{
			if(is_file($oldPath.$oldFilename))
			{ 
				rename($oldPath.$oldFilename, $newPath.$newFilename); 
				if($thbIndex != '')
				{
					global $thumb;
					if(isset($thumb[$thbIndex]))
					{
						if(count($thumb[$thbIndex]) > 0)
						{
							if(is_file($oldPath.'thumbs/'.$oldFilename))
							{ rename($oldPath.'thumbs/'.$oldFilename, $newPath.'thumbs/'.$newFilename); }
							$j=0;
							foreach($thumb[$thbIndex] as $thb)
							{
								if($j > 0)
								{
									if(is_file($oldPath.'thumbs/'.$thb['MAXW'].'_'.$oldFilename))
									{ rename($oldPath.'thumbs/'.$thb['MAXW'].'_'.$oldFilename, $newPath.'thumbs/'.$thb['MAXW'].'_'.$newFilename); }
								}
								$j++;
							}
						}
					}
				}
			}
		}
	}
	
	public function rotatePhoto($file, $direction='ccw', $newFilename='')
	{
		if(is_file($file))
		{
			if($newFilename == '')
			{ $newFilename = $file; }
			
			$extList = getValidImgExt();
			$info = pathinfo($file);
			if($extList[$info['extension']] != '')
			{ $fileType = $extList[$info['extension']]; }
			
			switch ($fileType) 
			{
				case 'image/pjpeg':
				$newimage = imagecreatefromjpeg($file);
				break;
				case 'image/jpeg':
				$newimage = imagecreatefromjpeg($file);
				break;
				case 'image/x-png':
				$newimage = imagecreatefrompng($file);
				break;
				case 'image/png':
				$newimage = imagecreatefrompng($file);
				break;
				case 'image/gif':
				$newimage = imagecreatefromgif($file);
				break;
			}	
			if($newimage)
			{
				if($direction == 'ccw')
				{ $rotate = imagerotate($newimage, 90, 0); }
				else
				{ $rotate = imagerotate($newimage, 270, 0); }
				
				if(($newFilename != $file) && (is_file($file)))
				{ unlink($file); }
				
				switch ($fileType) 
				{
					case 'image/pjpeg':
						imagejpeg($rotate, $newFilename, 100);
					break;
					case 'image/jpeg':
						imagejpeg($rotate, $newFilename, 100);
					break;
					case 'image/x-png':
						imagepng($rotate, $newFilename);
					break;
					case 'image/png':
						imagepng($rotate, $newFilename);
					break;
					case 'image/gif':
						imagegif($rotate, $newFilename);
					break;
				}	
				return true;
			}
		}
		else
		{ return false; }
	}
	
	public function getImageFont($text1, $text2='', $font='', $size='', $height, $width)
	{ return '<img src="'.SITE_URL.'images/imagefont/text.php?text='.$text1.'&amp;text2='.$text2.'&amp;size=15&amp;color=FFFFFF&amp;color2=F8AD02" />'; }
	public function getImageF($text1, $text2='', $font='', $size='', $height, $width)
	{ return '<img src="'.SITE_URL.'images/imagefont/text.php?text='.$text1.'&amp;text2='.$text2.'&amp;size=15&amp;color=FFFFFF&amp;color2=F8AD02" />'; }
	public function getImageF2($text1, $text2='', $font='', $size='', $height=0, $width=0)
	{ return '<img src="'.SITE_URL.'images/imagefont/text2.php?text='.$text1.'&amp;text2='.$text2.'&amp;size=15&amp;color=FFFFFF&amp;color2=F8AD02" />'; }
}
?>